<template>
    <div class="login_container">
        <el-container style="height:100%">
            <el-aside width="200px">
                <el-menu :default-active="menuActive.id" @select="menuSelectFn" class="el-menu-vertical-demo"
                    background-color="#666699" text-color="#fff" active-text-color="#ffd04b" style="height:100%">
                    <el-menu-item :index="item.id" v-for="(item, index_) in menuData" :key="index_">
                        <i :class="item.icon"></i>
                        <span slot="title">{{item.name}}</span>
                    </el-menu-item>

                    <el-input type="tex" v-model="menuText"
                        style="position: absolute; bottom: 38px; display: flex; width:100%;" placeholder="输入要添加或删除的分类名">
                    </el-input>
                    <div style="position: absolute; bottom: 2px; display: flex; width:100%;">
                        <div @click="removeMenu()" class="laber" style="color: #db5b5b;">删除</div>
                        <div @click="createrMenu" class="laber" style="color: #4eed95;">创建</div>
                    </div>
                </el-menu>
            </el-aside>
            <el-main>
                <div style="max-width: 100%; width: 100%; display: block; overflow-y: scroll;">
                    <div class="textareaContent">
                        <el-input type="textarea" v-model="newToDo" @keyup.ctrl.enter.native="newToDoFn(newToDo)"
                            autosize :rows="1" name="newToDoClass" placeholder="添加任务  [Ctrl+Enter 快速添加]">
                        </el-input>
                        <el-button size="small" @click="newToDoFn(newToDo)">添加任务</el-button>
                    </div>
                    <div class="toDoClass" v-if="NoCompleteChildren.length>0" style="">
                        <div class="toDoClass-item" v-for="(item, index_) in NoCompleteChildren" :key="index_">
                            <div style="width: 100%; display: flex;">
                                <el-switch v-model="item.completeFlag" @change="switchItemFn(item.id, index_)"
                                    title="设置为完成" active-color="#ff4949" inactive-color="#13ce66">
                                </el-switch>
                                <el-input type="textarea" :value="item.content" @dblclick.native="edit_(index_, $event)"
                                    @focus="edit_blur($event, index_)" autosize :disabled="item.textareaDisabled"
                                    :rows="1" placeholder="编辑任务">
                                </el-input>
                                <el-button size="mini" type="danger" plain @click="deleteToDoFn(item.id, index_)">删除任务
                                </el-button>
                            </div>
                            <div
                                style="display: flex; justify-content: end; font-size: 10px; position: absolute; bottom: -2px; right: 0; user-select: none;margin-right: 90px;">
                                <div style="color: #90939982;" type="info">
                                    创建时间：{{dateFormat(item.createdDate, "Y-m-d H:i:s")}}</div>
                                <!-- <div style="color: #67c23a7a; padding-left:12px;" type="success">完成时间：{{item.completeDate}}</div> -->
                            </div>
                        </div>
                    </div>
                    <div class="timeLine" v-if="CompleteChildren.length > 0">
                        <div
                            style="position: absolute; right: 0; display: flex; align-items: center; justify-content: end;z-index: 1;margin-right: 18px; font-size: 14px; color: #a8bf35;cursor: context-menu;">
                            排序:
                            <el-radio v-model="showTimeType" @change="CompleteChildrenRefresh('0')" label="0"
                                style="margin-left: 10px;">创建时间
                            </el-radio>
                            <el-radio v-model="showTimeType" @change="CompleteChildrenRefresh('1')" label="1">完成时间
                            </el-radio>
                        </div>
                        <div class="timeLine-subject">
                            <div class="timeLine-line"></div>
                            <div class="timeLine-item" v-for="(item, index_) in CompleteChildren" :key="index_">
                                <div v-if="isShowDatetime(CompleteChildren, item, index_)"
                                    style="display: flex; margin-bottom: 46px;">
                                    <div class="toDo-time">
                                        <div class="toDo-D">{{dateFormat(item.createdDate, "d")}}</div>
                                        <div class="toDo-M">{{dateFormat(item.completeDate, "m")}}</div>
                                    </div>
                                </div>
                                <div class="toDo-item">
                                    <div style="width: 100%; display: flex; justify-content: center;">
                                        <el-switch v-model="item.completeFlag"
                                            @change="switchItemFn_Complete(item.id, index_)" title="还原为未完成"
                                            style="height: auto; margin: 0 15px;" active-color="#ff4949"
                                            inactive-color="#13ce66">
                                        </el-switch>
                                        <pre
                                            style="white-space: pre-wrap;width:100%;cursor: context-menu;padding:0 5px;font-size: 18px;">{{item.content}}</pre>
                                        <el-button size="mini" type="danger" plain
                                            @click="deleteToDoFn_Complete(item.id, index_)">删除任务
                                        </el-button>
                                    </div>
                                    <div
                                        style="display: flex; justify-content: end; font-size: 10px; position: absolute; bottom: -2px; right: 0; user-select: none;margin-right: 90px;">
                                        <div style="color: #90939982;" type="info">
                                            创建时间：{{dateFormat(item.createdDate, "Y-m-d H:i:s")}}</div>
                                        <div style="color: #67c23a7a; padding-left:12px;" type="success">
                                            完成时间：{{dateFormat(item.completeDate, "Y-m-d H:i:s")}}</div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <!-- <div class="paging">1</div> -->
                    </div>
                </div>
                <!-- <div>
                    123
                </div> -->
            </el-main>
        </el-container>
    </div>
</template>

<script>
    import db from './myDriver.js';
    import Tool from '../assets/js/Tool.js';
    export default {
        components: {},
        data() {
            return {
                menuText: '', // 用于删除和创建分类
                newToDo: '', // 新增任务的具体信息
                menuActive: {}, // 表示激活那个菜单
                menuData: [], // 所有数据
                NoCompleteChildren: [], // 未完成的任务
                CompleteChildren: [], // 未完成的任务
                showTimeType: '0', // 控制完成的时间线：按照什么顺序显示
            };
        },
        created() {
            this.created();
            window.db = db
        },
        mounted() {},
        methods: {
            created() {
                /** 初始化  @author weijun.wu */
                let than = this;
                db.open(() => {
                    db.labe_getAll((res) => {
                        than.menuData = res;
                        let menuActiveIndex = localStorage.getItem('menuActiveIndex')
                        if (menuActiveIndex) {
                            than.menuActive = res.find((item) => item.id == menuActiveIndex);
                            than.menuActive || (
                                than.menuActive = res[0],
                                localStorage.setItem('menuActiveIndex', res[0].id)
                            )
                        } else {
                            than.menuActive = res[0]
                        }
                        than.NoCompleteChildrenRefresh();
                        than.CompleteChildrenRefresh();
                    })
                });
                this.showTimeType = localStorage.getItem("showTimeType")
            },
            // 
            // =====================  菜单部分
            // 
            menuSelectFn(index) {
                /** 选择菜单  @author weijun.wu */
                this.menuActive = this.menuData.find((item) => item.id == index) || this.menuData[0];
                this.NoCompleteChildrenRefresh();
                this.CompleteChildrenRefresh();
                localStorage.setItem('menuActiveIndex', index);
            },
            createrMenu() {
                let name = this.menuText.trim();
                let than = this;
                if (name) {
                    if (than.menuData.find((item) => name == item.name)) {
                        alert("已经存在了哦！！");
                        return;
                    };
                    db.labe_insert({
                        "id": new Date().getTime().toString(),
                        "name": name,
                        "icon": "el-icon-star-off",
                    })
                    db.labe_getAll((res) => {
                        than.menuData = res;
                    })
                    this.menuText = ""
                }
            },
            removeMenu() {
                let name = this.menuText.trim();
                let than = this;
                if (name && than.menuData.length > 1) {
                    let target = than.menuData.find((item) => {
                        return name == item.name
                    })
                    db.labe_delete(target.id)
                    db.labe_getAll((res) => {
                        than.menuData = res;
                    })
                    this.menuText = ""
                }
                name && than.menuData.length == 1 && alert("\n\n亲，最后坚持了哦！！\n\n不能再继续了！")
            },
            // 
            // =====================  未完成任务的部分
            // 
            newToDoFn(value) {
                /** 新增一个事项。  @author weijun.wu */
                let than = this;
                // this.NoCompleteChildren.push({})
                db.toDo_insert({
                    "id": new Date().getTime().toString(),
                    "menu": than.menuActive.name, // 分类的名字
                    "menuId": than.menuActive.id, // 分类的id
                    "content": value,
                    "complete": 0,
                    "completeFlag": false,
                    "textareaDisabled": true, // 给textarea设置不能修改能力
                    "createdDate": new Date().getTime(),
                    // "completeDate": "2021-10-17"
                })
                this.NoCompleteChildrenRefresh();
                this.newToDo = "";
            },
            switchItemFn(id, index_) {
                /** 设置开关，表示完成该事项  @author weijun.wu */
                let than = this;
                this.NoCompleteChildren[index_].complete = 1; // 给开关设置值
                this.NoCompleteChildren[index_].completeFlag = true; // 给开关设置值
                this.NoCompleteChildren[index_].completeDate = new Date().getTime();
                db.toDo_update(this.NoCompleteChildren[index_])
                setTimeout(() => {
                    than.NoCompleteChildrenRefresh();
                    than.CompleteChildrenRefresh();
                }, 200);
            },
            deleteToDoFn(id, index_) {
                /** 删除对应id的事项  @author weijun.wu */
                let than = this;
                // this.NoCompleteChildren.splice(index_, 1)
                db.toDo_delete(this.NoCompleteChildren[index_].id);
                this.NoCompleteChildrenRefresh();
            },
            edit_(index, event) {
                /** 双击事项，进行编辑事项。  @author weijun.wu */
                this.NoCompleteChildren[index].textareaDisabled = false;
                this.$nextTick(() => {
                    event.toElement.focus()
                })
                db.toDo_update(this.NoCompleteChildren[index])
            },
            edit_blur(event, index) {
                /**  因为vue的blur事件不能直接设置，所以通过focus的方式来设置。
                 * 该方法是事项修改好后进行保存值操作。  @author weijun.wu */
                let than = this;
                event.target.onblur = function (e) {
                    than.NoCompleteChildren[index].textareaDisabled = true; // 去掉textarea的编辑能力。使之只读。
                    than.NoCompleteChildren[index].content = e.target._value;
                    db.toDo_update(than.NoCompleteChildren[index])
                }
            },
            NoCompleteChildrenRefresh() {
                /** 刷新未完成的数据  @author weijun.wu */
                let than = this;
                db.getAllNoCompleteTodo(than.menuActive.id, (res) => {
                    than.NoCompleteChildren = res;
                }, than.menuActive.name)
            },
            // 
            // =====================  完成任务的部分
            // 
            CompleteChildrenRefresh(type) {
                /** 刷新完成的数据  @author weijun.wu */
                let than = this;
                type && localStorage.setItem("showTimeType", type)
                type || (type = localStorage.getItem("showTimeType"))
                db.getAllCompleteTodo(than.menuActive.id, (res) => {
                    type == 0 && res.sort((a, b) => b.createdDate - a.createdDate); // 排序。按照创建时间进行排序，最近创建的排在前面
                    type == 1 && res.sort((a, b) => b.completeDate - a.completeDate); // 排序。按照创建时间进行排序，最近创建的排在前面
                    // 显示多少条数据
                    let pageSum = 10
                    if (res.length > pageSum) { // 只显示前面的n条
                        than.CompleteChildren = res.slice(0, pageSum);
                        return;
                    }
                    than.CompleteChildren = res || []
                }, than.menuActive.name)
            },
            switchItemFn_Complete(id, index_) {
                /** 设置开关，表示完成该事项  @author weijun.wu */
                let than = this;
                this.CompleteChildren[index_].complete = 0; // 给开关设置值
                this.CompleteChildren[index_].completeFlag = false; // 给开关设置值
                this.CompleteChildren[index_].completeDate = '';
                db.toDo_update(this.CompleteChildren[index_])
                setTimeout(() => {
                    than.NoCompleteChildrenRefresh();
                    than.CompleteChildrenRefresh();
                }, 200);
            },
            deleteToDoFn_Complete(id, index_) {
                /** 删除对应id的事项  @author weijun.wu */
                let than = this;
                // this.NoCompleteChildren.splice(index_, 1)
                db.toDo_delete(this.CompleteChildren[index_].id);
                this.CompleteChildrenRefresh();
            },
            isShowDatetime(obj, item, index_) {
                /** 判断是否显示时间  @author weijun.wu */
                if (index_ == 0) return true;
                else if (Tool.dateFormat(item.createdDate, "d") == Tool.dateFormat(obj[index_ - 1].createdDate, "d")) {
                    return false;
                } else {
                    return true;
                }
            },
            // 
            // =====================  其他
            // 
            dateFormat(timestamp, formats) {
                return Tool.dateFormat(timestamp, formats);
            },
            saveData() { // 保存事项到本地
                // localStorage.setItem('storageData', JSON.stringify(this.menuData));
            },
        },
        watch: {
            // menuData: {
            //     handler: function (val, oldVal) {
            //         // 防抖 ....
            //         let than = this;
            //         clearTimeout(this.debounceTimeout || null);
            //         this.debounceTimeout = setTimeout(() => {
            //             than.saveData();
            //         }, 500);
            //         // 防抖 ....
            //     },
            //     deep: true
            // },
        },
    };
</script>

<style scoped></style>